import request from '../../utils/api/request'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //是否显示投票按钮
    flagBtn:true,
    //匿名
    userId:null,
    anonymous:null,
    title:'',
    describe:'',
    stopTime:null,
    type:null,
    voteDateList:[],
    //总的投票数量
    voteNumAll:null,
    //当前投票页的标识id
    voteId:null,
    code:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options,'options',getCurrentPages()[0].options)
    let userId
    if(options) {
      userId = wx.getStorageSync('userId')
      this.setData({
        voteId:options.id,
        userId
      })
      this.getVoteInfo(options.id)
    }else{
      userId = wx.getStorageSync('userId')
      let voteId = getCurrentPages()[0].options.id
      this.setData({
        voteId,
        userId
      })
      this.getVoteInfo(voteId)
    }


  },


  //根据唯一标识获取信息
  async getVoteInfo(vote_id){ 
    const result = await request(
                    '/api/front/vote/getVoteDetailData',
                    {vote_id}
                   )
    if( result.err_code == 200 ){
      let voteDateList = result.data.option.map(item => {
        item.currentUserVote = false
        item.showUserName = false
        return item
      })
      this.setData({
        voteDateList,
        title: result.data.title,
        stopTime: result.data.end_time,
        describe: result.data.describe,
        type: result.data.type*1,
        anonymous: result.data.anonymous *1
      })
      console.log(typeof this.data.anonymous)

      let voteNumAll = this.data.voteDateList.reduce((pre,item,index)=>{
        return pre+item.number
      },0)
      this.setData({voteNumAll})
      return 
    }
  },

  // 切换是否显示用户名icon
  switchImg(ev){
    //获取当前点击的选项索引
    let currentIndex = ev.target.dataset.showusername
    this.setData({
      //将当前的索引的showUserName取反判断是否显示用户名
      voteDateList : this.data.voteDateList.map((item,index)=>{
        if (index == currentIndex ){
          item.showUserName = !item.showUserName
          return item
        }
        return item
      })
    })
  },
  //投票事件
  voteEvent(ev){
    let { anonymous,flagBtn,stopTime } = this.data
    //超过截止日期
    if ( new Date( stopTime ) <  new Date( new Date() )  ){
      wx.showToast({
        title: '该投票已截止!',
        icon:'none'
      })
      return
    }

    if ( !flagBtn ) return


    //判断是否已登录
    let userInfo = wx.getStorageSync('userInfo') || {}
    //未登录且该投票不允许匿名,让用户登录，0是匿名1是没匿名
    if( (!userInfo || (JSON.stringify(userInfo) == "{}")) && anonymous){

      wx.login({
        success: (res) =>{
          if (res.code) {
            console.log(res.code)
            this.setData({
              code:res.code
            })
          }
        }
      })
  
  
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: async (res) => {
          let result = await request(
                              '/api/front/user/basic/wx_login',
                              {code:this.data.code,name:res.userInfo.nickName,img:res.userInfo.avatarUrl}
                            )
          if ( result.err_code == 200){
            this.setData({
              userInfo: res.userInfo,
              user_id: result.data.user_id
            })
            wx.setStorageSync('userInfo',res.userInfo)
            wx.setStorageSync('openId', result.data.openid)
            wx.setStorageSync('userId', result.data.user_id)
            
          }else{
            wx.showToast({
              title: '网络错误',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
  
    }else{
      //已登录
      this.saveVoteEvent(ev)
    }


    
  },
  //计算投票功能
  saveVoteEvent(ev){
    let { type } = this.data
    const currentItem = ev.currentTarget.dataset.currentitem
    //多选
    if ( type ){
      this.checkVote(currentItem)
    }else{
      //单选
      this.radioVote(currentItem)
    }
  },

  //多选
  checkVote(currentItem,type){
    let voteDateList = this.data.voteDateList.map((item,index)=>{
      if (item.id == currentItem.id){
        item.currentUserVote = !currentItem.currentUserVote
        //标识已投票
        // item.currentUserVote = true
        //判断是否已投票，并对票数进行计算
        item.currentUserVote ?  ++item.number : --item.number
        return item
      }
      return item
    })
    this.setData({voteDateList})
    //重新计算总票数
    let voteNumAll = this.data.voteDateList.reduce((pre,item,index)=>{
      return pre+item.number
    },0)
    this.setData({voteNumAll})
  },

  //单选
  radioVote(currentItem,type){
    if ( currentItem.currentUserVote ){
      return
    }
    let voteDateList = this.data.voteDateList.map((item,index)=>{
      if (item.id == currentItem.id){
        item.currentUserVote = !currentItem.currentUserVote
        //标识已投票
        // item.currentUserVote = true
        //判断是否已投票，并对票数进行计算
        item.currentUserVote ?  ++item.number : --item.number 
        return item
      }
      item.currentUserVote ? --item.number : null
      item.currentUserVote = false
      item.number 
      return item
    })
    this.setData({voteDateList})
    //重新计算总票数
    let voteNumAll = this.data.voteDateList.reduce((pre,item,index)=>{
      return pre+item.number
    },0)
    this.setData({voteNumAll})
  },

  //保存
  async submit(){

    let { type,anonymous,voteDateList } = this.data
    let user_id = wx.getStorageSync('userId')
    console.log(user_id,typeof anonymous)
    //未登录且投票页是匿名
    let option_id = []
    voteDateList.forEach(item =>{
      if ( !type ){
         item.currentUserVote ?  option_id = item.id  :null
        return
      }
      item.currentUserVote ?  option_id.push(item.id) :null
    })

    if( option_id.length === 0) return
    console.log(option_id)
    // return


    let result 
    if (  !user_id && !anonymous ){
      //匿名投票且没登录
      result = await request(
        '/api/front/vote/anonymous_vote',
        {
          option_id,
          user_id:null,
          type
        }
      )
    }else if ( !user_id && anonymous ){

      //非匿名投票且没有登录
      wx.showToast({
        title: '请先登录',
        icon:'none'
      })
      wx.navigateTo({
        url:'pages/home/home'
      })
      console.log('准备跳转')

      // wx.navigateTo({
      //   url:`/pages/home/home`
      // })
      console.log('跳转')
      return
    }else{
      //匿名投票但有登录 或 非匿名投票但登录
      result = await request(
        '/api/front/vote/no_anonymous_vote',
        {
          option_id,
          user_id,
          type
        }
      )
    }
    if ( result.err_code == 200 ){
      //投票成功
      wx.showToast({
        title: result.message,
        icon:'none'
      })
      this.setData({
        //将提交按钮隐藏
        flagBtn:false
      })
      // this.getVoteInfo(this.data.voteId)
      return
    }
    //投票失败
    wx.showToast({
      title: result.message,
      icon:'none'
    })
    //将已经投票的减退
    voteDateList = voteDateList.map(item =>{
      if (  item.currentUserVote ){
        this.setData({
          voteNumAll: --this.data.voteNumAll
        })
        item.number -= 1
        item.currentUserVote = false
      }
      return item
    })
    this.setData({
      voteDateList
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})